package init;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;


public class NacosDataSourceInitFunc implements InitFunc {
	String nacosAddr = "127.0.0.1:8848", group = "DEFAULT_GROUP", dataId = "RuleWithModePushByNacos_flow_rule.json"; 

	@Override
    public void init() throws Exception {
		// 流控规则转化器
		Converter<String, List<FlowRule>> nacosRulesConverter = new Converter<String, List<FlowRule>>() {
			@Override
			public List<FlowRule> convert(String source) {
				try {
					System.out.println("读取：" + source);
					if( source != null ){
						ObjectMapper objectMapper = new ObjectMapper();
						JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, FlowRule.class);
						List<FlowRule> readValue = objectMapper.readValue(source, javaType);
						return readValue;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return List.of() ;
			}
		};
		
		// 创建流控规则的NacosDataSource(读DataSource)
		ReadableDataSource<String, List<FlowRule>> flowRuleDataSource =  new NacosDataSource<>( nacosAddr, group, dataId, nacosRulesConverter );
        // 将可读数据源注册至FlowRuleManager
        // 这样当规则文件发生变化时，就会更新规则到内存
    	FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    }
}
